package com.shop.user.controller;

//import com.shop.user.entity.User;
//import com.shop.user.http.HttpResult;
import com.base.common.entity.User;
import com.base.common.http.HttpResult;
import com.base.common.utils.Md5Salt;
import com.shop.user.service.UserService;
import com.shop.user.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping( value = "/userlogin", method = RequestMethod.POST)
    public HttpResult login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        try {
            User user = userService.userLogin(username, Md5Salt.getMD5(password));
            String token = KeyUtil.genUniqueKey();
            if(user == null) {
                return HttpResult.error("账号或密码错误");
            }
            // 有效期1天 24*60*60 = 86400
            boolean isBool = redisUtils.set(token, user, 86400);
            if (isBool == false) {
                return HttpResult.error("设置redis失败");
            }
//            CookieUtils.setCookie(request, response,
//                    "shop_user1",
//                    JsonUtils.objectToJson(user),
//                    86400,
//                    true);
//            CookieUtils.setCookie(request, response,
//                    "shop_token1",
//                    token,
//                    86400,
//                    true);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("userInfo", user);
            return HttpResult.ok(map);
        } catch (Exception e) {
            return HttpResult.ok("登录失败");
        }

    }
}
